<!DOCTYPE html>
<html>
  
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  <meta name="author" content="Amos Zhu">
  
  
  <title>SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（四）——Nginx+Redis+Cache实现三级缓存架构 | Amos的技术博客</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="stuff,redis,spring boot,nginx,memcache,">
  

  
  <meta name="description" content="前几篇博文我们介绍了三级缓存架构的内容，并且实现了基于Nginx的定向请求分发的功能，那么接下来我们依次来编写Nginx缓存，redis缓存和Tomcat堆缓存的代码实现">

  

  
    <script src="//cdn.jsdelivr.net/npm/leancloud-storage@3.11.1/dist/av-min.js" async></script>
  

  
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async></script>
  

  
    <script src="//unpkg.com/valine/dist/Valine.min.js" async></script>
  

  

  <script>
  // theme-ad's config script
  // it can be used in every script
  
  window.AD_CONFIG = {
    leancloud: {"appid":"eObxCkTJ6j4GzRxGLgiHyfJa-gzGzoHsz","appkey":"fzRMAFC6MCE11mp7mnvh4Kwe","comment":true,"count":true},
    welcome: {"enable":true,"interval":30},
    start_time: "2019-05-28",
    passwords: ["efe07af7441da2b69c4a41e42e73be4db47f66010a56900788a458354a7373ec", ],
    is_post: true,
    lock: false,
    author: "Amos Zhu",
    share: {"qq":true,"wechat":true},
    mathjax: true,
    page_type: "",
    root: "/blog/"
  };
</script>

  <script src="/blog/vendor/sha256.min.js"></script>
<script src="/blog/js/auth.js"></script>
<script src="/blog/js/index.js"></script>
<script src="/blog/vendor/qrcode.min.js"></script>

  
    <link rel="icon" href="/blog/images/favicon.ico">
    <link rel="apple-touch-icon" href="/blog/images/touch-icon.png">
  

  <link href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <link rel="stylesheet" href="/blog/css/index.css">
<link rel="stylesheet" href="/blog/styles/components/highlight/highlight.css">

  
</head>
  <body>
    <header class="site-header">
  <div class="site-header-brand">
    
      <span class="site-header-brand-title">
        <a href="/blog/">Amos Zhu</a>
      </span>
    
    
      <span class="site-header-brand-motto"> | 当浮躁的心静不下，不妨写些东西或者看会书</span>
    
  </div>
  <div class="site-header-right">
    <nav class="site-header-navigation">
      
        <a href="/blog/" target="_self">首页</a>
      
        <a href="/blog/archives/" target="_self">归档</a>
      
        <a href="/blog/tags/" target="_self">标签</a>
      
        <a href="/blog/categories/" target="_self">分类</a>
      
        <a href="/blog/redis/" target="_self">redis</a>
      
        <a href="/blog/rabbitMQ/" target="_self">rabbitMQ</a>
      
        <a href="/blog/elasticsearch" target="_self">elasticsearch</a>
      
        <a href="/blog/stuff" target="_self">stuff</a>
      
        <a href="/blog/kafka" target="_self">kafka</a>
      
        <a href="/blog/friends/" target="_self">友链</a>
      
        <a href="/blog/about/" target="_self">关于</a>
      
    </nav>
    <div class="site-header-btn">
      
        <a href="https://gitee.com/amos_zhu" target="_blank" id="site-github">
          <i class="fa fa-github-alt"></i>
        </a>
      
      <a href="javascript:void(0);" id="site-search">
        <i class="fa fa-search"></i>
      </a>
      <a href="javascript:void(0);" id="site-nav-btn">
        <i class="fa fa-ellipsis-v"></i>
      </a>
    </div>
  </div>
</header>
<nav class="table-content" id="site-nav">
  <div class="table-content-title">
    <span>导航</span>
  </div>
  <div class="table-content-main">
    <ol class="toc">
      
        <li class="toc-item">
          <a href="/blog/" target="_self">
            首页
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/archives/" target="_self">
            归档
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/tags/" target="_self">
            标签
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/categories/" target="_self">
            分类
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/redis/" target="_self">
            redis
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/rabbitMQ/" target="_self">
            rabbitMQ
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/elasticsearch" target="_self">
            elasticsearch
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/stuff" target="_self">
            stuff
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/kafka" target="_self">
            kafka
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/friends/" target="_self">
            友链
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/about/" target="_self">
            关于
          </a>
        </li>
      
    </ol>
  </div>
</nav>
<div id="site-process"></div>
    <main>
      
  <div class="passage">
  <div class="passage-meta">
    <span>
      <i class="fa fa-calendar"></i>2019-09-08
    </span>
    
      <span>
        | <a href="/blog/categories/stuff/"><i class="fa fa-bookmark"></i>stuff</a>
      </span>
    
    
      <span>
        | <i class="fa fa-unlock-alt"></i>UNLOCK
      </span>
    
  </div>
  <h1 class="passage-title">
    SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（四）——Nginx+Redis+Cache实现三级缓存架构
  </h1>
  
  <article class="passage-article">
    <h3 id="参考之前的博文"><a href="#参考之前的博文" class="headerlink" title="参考之前的博文"></a>参考之前的博文</h3><ul>
<li><a href="https://www.jianshu.com/p/73d95bb465df" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（一）——三级缓存架构体系</a></li>
<li><a href="https://www.jianshu.com/p/35ab81c31044" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（二）——Nginx环境安装和整合Lua</a></li>
<li><a href="https://www.jianshu.com/p/e8d07c1fa795" target="_blank" rel="noopener">SpringBoot+Redis+MemCache+Nginx+Lua实现三级缓存架构（三）——Nginx+Lua实现定向请求分发</a></li>
</ul>
<p>本博文今天主要基于Nginx+Lua+Redis+Cache实现三级缓存架构的代码实现，使用的平台代码，我们可以直接在<a href="https://www.jianshu.com/p/b6befa551933" target="_blank" rel="noopener">《缓存与数据库双写一致性的解决方案——附上代码解决方案》</a>的框架基础上来实现，具体的代码可以参考Gitee上的 <a href="https://gitee.com/amos_zhu/doubleWriterConsistence" target="_blank" rel="noopener">《doubleWriterConsistence》</a></p>
<p>第一篇博文已经整理了三级架构的业务逻辑，为了方便接下来我们代码的开发，我们再来整理下三级缓存架构的业务逻辑</p>
<p><img src="https://s2.ax1x.com/2019/08/30/mOO7ut.png" alt="image"></p>
<ul>
<li>用户请求过来首先经过Nginx的分发层来分发请求，对于同一访问定向请求到Nginx的应用层</li>
<li>Nginx应用层接收请求，判断Nginx本地有没有数据</li>
<li>如果有数据直接返回给用户，如果没有数据，则向Redis中请求获取数据</li>
<li>Redis中如果没有数据库，则会向Tomcat堆缓存中获取数据</li>
<li>如果Tomcat堆缓存中也没有数据的话，则最终会到数据库中获取数据</li>
<li>每层的数据获取都会到将数据保存到上一层的容器里面</li>
</ul>
<h3 id="Nginx-Lua对服务的定向请求访问"><a href="#Nginx-Lua对服务的定向请求访问" class="headerlink" title="Nginx+Lua对服务的定向请求访问"></a>Nginx+Lua对服务的定向请求访问</h3><p>在上一篇博文中，我们规划了三个服务器来作为Nginx的分发层和应用层<br>服务器 | 用途<br>—|—<br>192.168.56.105 | 分发层<br>192.168.56.106 | 应用层<br>192.168.56.107 | 应用层</p>
<p>并且已经整理好了Nginx分发层到应用层请求的功能，现在我们来实现Nginx接收分发层的参数，并且请求系统服务的功能</p>
<ol>
<li>搭建Nginx应用层渲染Html的环境</li>
</ol>
<p>我们需要使用一个html静态界面来展示我们获取的数据，Lua层需要依赖来支持</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 在我们的自定的lualib包中添加依赖支持</span></span><br><span class="line"><span class="built_in">cd</span> /home/work/lualib/resty/</span><br><span class="line"><span class="comment">## 下载template.lua</span></span><br><span class="line">wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template.lua</span><br><span class="line"><span class="comment">## 创建html模板的文件夹，放置以后的html模板</span></span><br><span class="line">mkdir /home/work/lualib/resty/html</span><br><span class="line"><span class="comment">## 在该文件夹下，添加html.lua</span></span><br><span class="line">wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template/html.lua</span><br></pre></td></tr></table></figure>
<p>然后我们在应用层的nginx.conf中添加访问模板的路径配置</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">   <span class="comment">-- vi /home/work/conf/nginx.conf</span></span><br><span class="line">   server &#123;</span><br><span class="line">   listen <span class="number">80</span>;</span><br><span class="line">   server_name _;</span><br><span class="line">   set $template_location <span class="string">"/templates"</span>;  </span><br><span class="line">   set $template_root <span class="string">"/home/work/templates"</span>;</span><br><span class="line">   location /lua &#123;</span><br><span class="line">      default_type text/html;</span><br><span class="line">      content_by_lua_file /home/work/conf/lua/requestDirect.lua;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 创建templates的模板目录</span></span><br><span class="line">mkdir /home/work/templates</span><br><span class="line"><span class="comment">## 创建 requestDirect.html</span></span><br><span class="line">vi requestDirect.html</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--我们只做展示使用 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">title</span>&gt;</span>192.168.56.107<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bddy</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">div</span>&gt;</span>request_direct:&#123;* name *&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>再同样设置另一个应用层的nginx</p>
<p>在Nginx中如果想使用共享缓存的话，需要在 nginx.conf中设置缓存的大小<br><figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 修改/usr/local/openresty/nginx/conf/nginx.conf，添加缓存的支持 在http的模块中添加如下的配置</span></span><br><span class="line">lua_shared_dict my_cache <span class="number">128</span>m;</span><br></pre></td></tr></table></figure></p>
<p>配置完成之后，我们来编写应用层调用服务和返回结果保存nginx缓存和渲染界面的代码</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> uri_args = ngx.req.get_uri_args()</span><br><span class="line"><span class="comment">-- 获取参数id</span></span><br><span class="line"><span class="keyword">local</span> id = uri_args[<span class="string">"id"</span>]</span><br><span class="line"><span class="comment">-- 获取nginx缓存</span></span><br><span class="line"><span class="keyword">local</span> cache_ngx = ngx.shared.my_cache</span><br><span class="line"><span class="comment">-- 定义缓存的key</span></span><br><span class="line"><span class="keyword">local</span> idCacheKey = <span class="string">"id_"</span>..id</span><br><span class="line"><span class="comment">-- 根据key获取缓存</span></span><br><span class="line"><span class="keyword">local</span> idCache = cache_ngx:get(idCacheKey)</span><br><span class="line"><span class="comment">-- 如果缓存为空的话 定向请求</span></span><br><span class="line"><span class="keyword">if</span> idCache == <span class="string">""</span> <span class="keyword">or</span> idCache == <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">	<span class="keyword">local</span> http = <span class="built_in">require</span>(<span class="string">"resty.http"</span>)</span><br><span class="line">	<span class="keyword">local</span> httpc = http.new()</span><br><span class="line">    <span class="comment">-- 这里的ip是业务层的ip地址和端口号</span></span><br><span class="line">	<span class="keyword">local</span> resp, err = httpc:request_uri(<span class="string">"http://192.168.56.1:8080"</span>,&#123;</span><br><span class="line">  		method = <span class="string">"GET"</span>,</span><br><span class="line">  		<span class="built_in">path</span> = <span class="string">"/load?id="</span>..id</span><br><span class="line">	&#125;)</span><br><span class="line">    <span class="comment">-- 将返回结果赋值给缓存变量</span></span><br><span class="line">	idCache = resp.body</span><br><span class="line">	<span class="comment">-- 设置缓存并且添加失效时间</span></span><br><span class="line">	cache_ngx:set(idCacheKey, idCache, <span class="number">10</span> * <span class="number">60</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 加载cjson插件</span></span><br><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span>(<span class="string">"cjson"</span>)</span><br><span class="line"><span class="keyword">local</span> idCacheJSON = cjson.decode(idCache)</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> context = &#123;</span><br><span class="line">	name = idCacheJSON.name</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> template = <span class="built_in">require</span>(<span class="string">"resty.template"</span>)</span><br><span class="line"><span class="comment">-- 渲染html数据</span></span><br><span class="line">template.render(<span class="string">"requestDirect.html"</span>, context)</span><br></pre></td></tr></table></figure>
<p>lua层的代码开发完成之后，我们来校验下编写的是否有问题<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 查看是否有编写的问题</span></span><br><span class="line">nginx -t</span><br><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure></p>
<h3 id="Tomcat堆缓存设置"><a href="#Tomcat堆缓存设置" class="headerlink" title="Tomcat堆缓存设置"></a>Tomcat堆缓存设置</h3><p>使用之前双写数据一致性的代码框架来编写，该框架中已经集成了操作redis的功能，现在我只需要在此基础上添加ehCache的功能，然后在此基础上编写业务代码即可</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 在maven中添加 ehcache的依赖--&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- Ehcache 坐标 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.ehcache<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>ehcache<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在resource目录下添加 ehcache.xml配置文件<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">config</span></span></span><br><span class="line"><span class="tag">        <span class="attr">xmlns:xsi</span>=<span class="string">'http://www.w3.org/2001/XMLSchema-instance'</span></span></span><br><span class="line"><span class="tag">        <span class="attr">xmlns</span>=<span class="string">'http://www.ehcache.org/v3'</span></span></span><br><span class="line"><span class="tag">        <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.1.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义缓存为堆内存--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">cache-template</span> <span class="attr">name</span>=<span class="string">"heap-cache"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">resources</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">heap</span> <span class="attr">unit</span>=<span class="string">"entries"</span>&gt;</span>2000<span class="tag">&lt;/<span class="name">heap</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">offheap</span> <span class="attr">unit</span>=<span class="string">"MB"</span>&gt;</span>100<span class="tag">&lt;/<span class="name">offheap</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">resources</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">cache-template</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 定义缓存别名--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">cache</span> <span class="attr">alias</span>=<span class="string">"inventory"</span> <span class="attr">uses-template</span>=<span class="string">"heap-cache"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">expiry</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 缓存失效时间--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ttl</span> <span class="attr">unit</span>=<span class="string">"seconds"</span>&gt;</span>40<span class="tag">&lt;/<span class="name">ttl</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">expiry</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">cache</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">config</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>最后在 <code>applicaiton.yml</code>中添加路径<br><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  cache:</span></span><br><span class="line"><span class="attr">    jcache:</span></span><br><span class="line"><span class="attr">      config:</span> <span class="string">classpath*:ehcache.xml</span></span><br></pre></td></tr></table></figure></p>
<p>这样ehcache就已经集成好了，下面我们开始编写业务代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: double-writer-consistence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: InventoryCacheServiceImpl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.doublewriterconsistence.service.impl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: zhuqb</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: Ehcache 缓存</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/8/30 0030 下午 16:06</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="meta">@Transactional</span>(readOnly = <span class="keyword">false</span>, rollbackFor = Exception.class)</span><br><span class="line"><span class="meta">@CacheConfig</span>(cacheNames = <span class="string">"inventory"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryCacheServiceImpl</span> <span class="keyword">implements</span> <span class="title">InventoryCacheService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    InventoryMapper inventoryMapper;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 从数据库中查询数据，并且加载数据到缓存</span></span><br><span class="line"><span class="comment">     * condition满足缓存条件的数据才会放入缓存，condition在调用方法之前和之后都会判断</span></span><br><span class="line"><span class="comment">     * unless用于否决缓存更新的，不像condition，该表达只在方法执行之后判断，此时可以拿到返回值result进行判断了</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@Cacheable</span>(key = <span class="string">"'id_'+#id"</span>, unless = <span class="string">"#result == null"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Inventory <span class="title">select</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.inventoryMapper.selectById(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 数据删除的时候，也删除堆缓存</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@CacheEvict</span>(key = <span class="string">"'id_'+#id"</span>)</span><br><span class="line">    <span class="meta">@Transactional</span>(readOnly = <span class="keyword">false</span>, rollbackFor = Exception.class)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.inventoryMapper.delete(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>定义Nginx请求后端的接口<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: double-writer-consistence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: InventoryCacheController</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.doublewriterconsistence.web</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: zhuqb</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>:</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/9/5 0005 下午 18:23</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryCacheController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    InventoryService inventoryService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    InventoryCacheService inventoryCacheService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * nginx定向请求</span></span><br><span class="line"><span class="comment">     * 1. 先从redis中查询，</span></span><br><span class="line"><span class="comment">     * 2. 如果redis中查询不到，则从ehcache中查询</span></span><br><span class="line"><span class="comment">     * 3. ehcache中查询不到，则从数据库总查询(这步包括在ehcache中)</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/load"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Inventory <span class="title">load</span><span class="params">(@RequestParam(<span class="string">"id"</span>)</span> String id) </span>&#123;</span><br><span class="line">        <span class="comment">// 先从redis中查询</span></span><br><span class="line">        Inventory inventory = <span class="keyword">this</span>.inventoryService.getInventoryCache(id);</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isEmpty(inventory)) &#123;</span><br><span class="line">            inventory = <span class="keyword">this</span>.inventoryCacheService.select(id);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> inventory;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>至此我们就完成了简单的三级缓存架构的框架，后端的代码是比较简单的，主要是理解三级缓存架构的流程，通过三级缓存来支持高并发时的访问，减少数据库的交互，同时降低缓存带来的一系列的风险</p>
  </article>
  <aside class="table-content" id="site-toc">
  <div class="table-content-title">
    <i class="fa fa-arrow-right fa-lg" id="site-toc-hide-btn"></i>
    <span>目录</span>
  </div>
  <div class="table-content-main">
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#参考之前的博文"><span class="toc-text">参考之前的博文</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Nginx-Lua对服务的定向请求访问"><span class="toc-text">Nginx+Lua对服务的定向请求访问</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Tomcat堆缓存设置"><span class="toc-text">Tomcat堆缓存设置</span></a></li></ol>
  </div>
</aside>
  
    <aside class="passage-copyright">
      <div>本文作者: Amos Zhu</div>
      
        <div>
          原文链接: 
          <a href target="_blank">http://amos_zhu.gitee.io/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（四）——Nginx-Redis-Cache实现三级缓存架构/</a>
        </div>
      
      <div>
        版权声明: 本博客所有文章除特别声明外, 均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议. 转载请注明出处!
      </div>
    </aside>
  
  
    <div class="passage-tags">
     
      <a href="/blog/tags/redis/"><i class="fa fa-tags"></i>redis</a>
     
      <a href="/blog/tags/spring-boot/"><i class="fa fa-tags"></i>spring boot</a>
     
      <a href="/blog/tags/nginx/"><i class="fa fa-tags"></i>nginx</a>
     
      <a href="/blog/tags/memcache/"><i class="fa fa-tags"></i>memcache</a>
    
    </div>
  
</div>

    </main>
    
      
<div class="site-comment-contanier" data-plateform="leancloud">
  
    <p id="site-comment-info">
      <i class="fa fa-spinner fa-spin"></i> 评论加载中
    </p>
    <div id="site-comment"></div>
  
</div>
    
    <div class="site-footer-wrapper">
  <footer class="site-footer">
    
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">博客推荐</h5>
          
            <span class="site-footer-item">
              <a href="http://youzhixueyuan.com/series/java" target="_blank">优知学院</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://ruanyifeng.com/" target="_blank">阮一峰的个人网站</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">系列教程</h5>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/redis" target="_blank">Redis系列教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/rabbitMQ/" target="_blank">RabbitMQ教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/kafka/" target="_blank">Kafka架构探险</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">抓到我</h5>
          
            <span class="site-footer-item">
              <a href="https://gitee.com/amos_zhu" target="_blank">Gitee</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://blog.csdn.net/wdcl2468" target="_blank">CSDN</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://www.jianshu.com/u/2dbe61b1f3c3" target="_blank">简书</a>
            </span>
          
        </div>
      
    
    <div class="site-footer-info">
      <i class="fa fa-clock-o"></i> 本站已稳定运行<span id="site-time"></span>
    </div>
    
      <div class="site-footer-info">
        <i class="fa fa-paw"></i> 您是本站第 <span id="site-count"></span> 位访客
      </div>
    
    
      <div class="site-footer-info">
        <i class="fa fa-at"></i> Email: amoszhu@aliyun.com
      </div>
    
    <div class="site-footer-info">
      <i class="fa fa-copyright"></i> 
      2019 <a href="https://github.com/dongyuanxin/theme-ad/" target="_blank">Theme-AD</a>.
      Created by <a href="https://godbmw.com/" target="_blank">GodBMW</a>.
      All rights reserved.
    </div>
  </footer>
</div>
    <div id="site-layer" style="display:none;">
  <div class="site-layer-content">
    <div class="site-layer-header">
      <span class="site-layer-header-title" id="site-layer-title"></span>
      <i class="fa fa-close" id="site-layer-close"></i>
    </div>
    <div class="site-layer-body" id="site-layer-container">
      <div class="site-layer-input" id="site-layer-search" style="display: none;">
        <div class="site-layer-input-choose">
          <a href="javascript:void(0);" title="Change Search Engine">Google</a>
        </div>
        <input type="text">
        <i class="fa fa-search"></i>
      </div>
      
        <div class="site-layer-reward" id="site-layer-reward" style="display: none;">
          
            <div>
              <img src="/blog/images/wechat.png" alt="WeChat">
              
                <p>WeChat</p>
              
            </div>
          
            <div>
              <img src="/blog/images/alipay.png" alt="AliPay">
              
                <p>AliPay</p>
              
            </div>
          
        </div>
      
      <div id="site-layer-welcome" style="display:none;"></div>
    </div>
  </div>
</div>
    

<div class="bottom-bar">
  <div class="bottom-bar-left">
    <a href="/blog/passages/Kafka架构探险（一）——Kafka的集群安装/" data-enable="true">
      <i class="fa fa-arrow-left"></i>
    </a>
    <a href="/blog/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（三）——Nginx-Lua实现定向请求分发/" data-enable="true">
      <i class="fa fa-arrow-right"></i>
    </a>
  </div>
  <div class="bottom-bar-right">
    <a href="javascript:void(0);" data-enable="true" id="site-toc-show-btn">
      <i class="fa fa-bars"></i>
    </a>
    
      <a href="#site-comment" data-enable="true">
        <i class="fa fa-commenting"></i>
      </a>
    
    <a href="javascript:void(0);" id="site-toggle-share-btn">
      <i class="fa fa-share-alt"></i>
    </a>
    
      <a href="javascript:void(0);" id="site-reward">
        <i class="fa fa-thumbs-up"></i>
      </a>
    
    <a href="javascript:void(0);" id="back-top-btn">
      <i class="fa fa-chevron-up"></i>
    </a>
  </div>
</div>
    <div id="share-btn">
  
  
  
  
    <a id="share-btn-qq" href="javascript:void(0);" target="_blank">
      <i class="fa fa-qq"></i>
    </a>
  
  
    <a id="share-btn-wechat" href="javascript:void(0);" target="_blank">
      <i class="fa fa-wechat"></i>
    </a>
  
</div>
    


  <script async>
  (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>



  <script async>
    (function(){
    var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?":"https://jspassport.ssl.qhimg.com/11.0.1.js?";
    document.write('<script src="' + src + '" id="sozz"><\/script>');
    })();
  </script>


    
  </body>
</html>